package com.rc.evcharger.service.handle;

import com.alibaba.fastjson.JSON;
import com.rc.evcharger.common.dto.CalculateDto;
import com.rc.evcharger.model.elec.ElecStationPrice;
import com.rc.evcharger.redis.RedChargeDataService;
import com.rc.evcharger.service.elec.ElecStationPriceService;
import com.rc.evcharger.vo.price.ElecStationPriceAssember;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Create by Yang on 2021/9/13
 */
@Component
public class ChargePriceHandler {
    private static Logger logger = LoggerFactory.getLogger(ChargePriceHandler.class);
    @Autowired
    private RedChargeDataService redChargeDataService;

    @Autowired
    private ElecStationPriceService elecStationPriceService;

    public ElecStationPrice lastPriceHandler(CalculateDto dto, ElecStationPrice elecStationPrice) {

        //获取历史时段单价
        String lastElecStationPriceStr = redChargeDataService.getOrderInfoCurrentPrice(dto.getPileRtua(), dto.getGunNum(), dto.getOrderNum());
        if (StringUtils.isEmpty(lastElecStationPriceStr)) {
            String jsonString = JSON.toJSONString(elecStationPrice);
            redChargeDataService.putOrderInfoCurrentPrice(dto.getPileRtua(), dto.getGunNum(), dto.getOrderNum(), jsonString);
            return null;
        }

        if (lastElecStationPriceStr != null) {
            /* bsp是保存上次充电的电费，服务费单价*/
            ElecStationPrice bsp = JSON.parseObject(lastElecStationPriceStr, ElecStationPrice.class);

            //todo 最近两个时段不一致
            if (bsp.getPriceId().longValue() != elecStationPrice.getPriceId().longValue()) {
                logger.info("最近两个时段不一致,创建分时段订单,订单号:{},旧电价ID:{}，新电价ID", bsp.getPriceId(), elecStationPrice.getPriceId());
                return bsp;
            }
        }
        return null;
    }


    public void putRedPricesHandler(String pileRtua, String gunNum, String orderNum, Long elecStationId) {
        //保存分时段单价列表
        String orderInfoPrices = redChargeDataService.getOrderInfoPrices(pileRtua, gunNum, orderNum);
        if (StringUtils.isEmpty(orderInfoPrices)) {
            List<ElecStationPrice> elecStationPrices = elecStationPriceService.listByStationId(elecStationId);

            //为空不保存
            if (CollectionUtils.isEmpty(elecStationPrices)) {
                logger.error("电价列表为空，不存redis,对应桩编号:{},订单号:{},站ID:{}", pileRtua, orderNum, elecStationId);
                return;
            }
            ElecStationPriceAssember elecStationPriceAssember = new ElecStationPriceAssember();
            elecStationPriceAssember.setElecStationPrices(elecStationPrices);

            String value = JSON.toJSONString(elecStationPriceAssember);
            redChargeDataService.putOrderInfoPrices(pileRtua, gunNum, orderNum, value);
        }
    }
}
